package com.nari.ncps.screen.service.impl.electric;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.electric.ElectricProdoperPowerGeneral;
import com.nari.ncps.screen.mapper.electric.ElectricProdoperHeatingMapper;
import com.nari.ncps.screen.service.electric.ElectricProdoperHeatingService;
import com.nari.ncps.screen.vo.electric.*;
import com.nari.ncps.screen.entity.electric.ElectricProdoperHeating;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 供热情况详情表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class ElectricProdoperHeatingServiceImpl extends ServiceImpl<ElectricProdoperHeatingMapper, ElectricProdoperHeating> implements ElectricProdoperHeatingService {


    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 供热计划完成情况
     * 注意：从 qt_dp_electric_prodoper_power_general 表查询发电数据（用于测试）
     *
     * @param year  年份（可选，默认当前年）
     * @param month 月份（可选，默认当前月）
     * @return 供热计划完成情况
     */
    @Override
    public GrPlanCompletionStatus grPlanCompletionStatus(Integer year, Integer month) {
        // 如果参数为空，使用当前年月
        if (year == null) {
            year = java.time.LocalDate.now().getYear();
        }
        if (month == null) {
            month = java.time.LocalDate.now().getMonthValue();
        }

        GrPlanCompletionStatus status = new GrPlanCompletionStatus();
        status.setYear(year);
        status.setMonth(month);

        try {

            LambdaQueryWrapper<ElectricProdoperHeating> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ElectricProdoperHeating::getOrgCode, "100360")
                    .eq(ElectricProdoperHeating::getDateType, 1)
                    .eq(ElectricProdoperHeating::getYear, year)
                    .eq(ElectricProdoperHeating::getMonth, month);
            ElectricProdoperHeating data = this.getOne(wrapper);
            List<FdPowerPlantSupplyComplateStatus> result = new ArrayList<>();
            // 处理月数据
            if (data != null) {
                status.setMonthlyPlanHeating(data.getMonthlyPlanHeating());
                status.setMonthlyActualHeating(data.getMonthlyActualHeating());
                if(data.getMonthlyActualHeating()!=null && data.getMonthlyPlanHeating()!=null
                && data.getMonthlyPlanHeating().compareTo(BigDecimal.ZERO) > 0&&data.getMonthlyActualHeating().compareTo(BigDecimal.ZERO) > 0){
                    status.setMonthlyCompletionRate(data.getMonthlyActualHeating().divide(data.getMonthlyPlanHeating(), 2, BigDecimal.ROUND_HALF_UP));
                }else{
                    status.setMonthlyCompletionRate(BigDecimal.ZERO);
                }
                status.setMonthlyOverShortage(data.getMonthlyActualHeating().subtract(data.getMonthlyPlanHeating()));
            } else {
                // 数据为空时，设置为0
                status.setMonthlyPlanHeating(BigDecimal.ZERO);
                status.setMonthlyActualHeating(BigDecimal.ZERO);
                status.setMonthlyOverShortage(BigDecimal.ZERO);
                status.setMonthlyCompletionRate(BigDecimal.ZERO);
            }

        } catch (Exception e) {
            // 如果查询出错，返回空数据，保证接口不报错
            System.err.println("查询供热计划完成情况出错: " + e.getMessage());
            e.printStackTrace();
            status.setMonthlyPlanHeating(BigDecimal.ZERO);
            status.setMonthlyActualHeating(BigDecimal.ZERO);
            status.setMonthlyOverShortage(BigDecimal.ZERO);
            status.setMonthlyCompletionRate(BigDecimal.ZERO);
        }

        return status;
    }

    /**
     * 供热量完成趋势
     *
     * @param year 年份（可选，默认当前年）
     * @return 包含今年和去年各月份供热量的趋势列表
     */
    @Override
    public List<GrComplateTrend> grComplateTrend(Integer year) {
        // 如果参数为空，使用当前年
        if (year == null) {
            year = java.time.LocalDate.now().getYear();
        }

        List<GrComplateTrend> result = new ArrayList<>();

        GrComplateTrendCopyVO copyMonthVO = new GrComplateTrendCopyVO();

        try {

            YearMonth currentYearMonth = YearMonth.now();
            String current = currentYearMonth.format(DateTimeFormatter.ofPattern("yyyyMM"));

            // 获取12个月之前的年月
            YearMonth twelveMonthsAgo = YearMonth.now().minusMonths(11);
            String startDate = twelveMonthsAgo.format(DateTimeFormatter.ofPattern("yyyyMM"));

            LambdaQueryWrapper<ElectricProdoperHeating> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ElectricProdoperHeating::getOrgCode, "100360")
                    .eq(ElectricProdoperHeating::getDateType, "1")
                    .ge(ElectricProdoperHeating::getStatisticTime, startDate)
                    .le(ElectricProdoperHeating::getStatisticTime, current)
                    .orderByAsc(ElectricProdoperHeating::getStatisticTime);
            List<ElectricProdoperHeating> dataList = this.list(wrapper);
            if (dataList == null || dataList.isEmpty()) {
                return new ArrayList<>();
            }


            if (dataList != null) {
                for (ElectricProdoperHeating data : dataList) {
                    GrComplateTrend vo = new GrComplateTrend();
                    vo.setYear(data.getYear());
                    vo.setMonth(data.getMonth());
                    if(data.getMonthlyPlanHeating()!=null
                            && data.getMonthlyPlanHeating().compareTo(BigDecimal.ZERO) > 0
                    &&data.getMonthlyActualHeating().compareTo(BigDecimal.ZERO)>0){
                        vo.setMonthlyCompletionRate(data.getMonthlyActualHeating().divide(data.getMonthlyPlanHeating(), 2, RoundingMode.HALF_UP));
                    }else {
                        vo.setMonthlyCompletionRate(BigDecimal.ZERO);
                    }
                    result.add(vo);
                    if(data.getMonth()==1) {
                        copyMonthVO.setMth_1(data.getMonthlyActualHeating());
                    } else if(data.getMonth()==2) {
                        copyMonthVO.setMth_2(data.getMonthlyActualHeating());
                    } else if(data.getMonth()==3) {
                        copyMonthVO.setMth_3(data.getMonthlyActualHeating());
                    } else if(data.getMonth()==4) {
                        copyMonthVO.setMth_4(data.getMonthlyActualHeating());
                    } else if(data.getMonth()==5) {
                        copyMonthVO.setMth_5(data.getMonthlyActualHeating());
                    } else if(data.getMonth()==6) {
                        copyMonthVO.setMth_6(data.getMonthlyActualHeating());
                    } else if(data.getMonth()==7) {
                        copyMonthVO.setMth_7(data.getMonthlyActualHeating());
                    } else if(data.getMonth()==8) {
                        copyMonthVO.setMth_8(data.getMonthlyActualHeating());
                    } else if(data.getMonth()==9) {
                        copyMonthVO.setMth_9(data.getMonthlyActualHeating());
                    } else if(data.getMonth()==10) {
                        copyMonthVO.setMth_10(data.getMonthlyActualHeating());
                    } else if(data.getMonth()==11) {
                        copyMonthVO.setMth_11(data.getMonthlyActualHeating());
                    } else if(data.getMonth()==12) {
                        copyMonthVO.setMth_12(data.getMonthlyActualHeating());
                    }
                }
            }

        } catch (Exception e) {
            // 如果查询出错，返回空数据，保证接口不报错
            System.err.println("查询供热量完成趋势出错: " + e.getMessage());
            e.printStackTrace();
            // 返回空列表
            result.clear();
        }
        for(GrComplateTrend cvo : result) {
            BeanUtils.copyProperties(copyMonthVO, cvo);
        }
        return result;
    }

    /**
     * 从数据库查询并设置月度数据
     *
     * @param trend GrComplateTrend对象
     * @param year  年份
     */
    private void setMonthlyDataFromDb(GrComplateTrend trend, Integer year) {
        // 查询月度数据（date_type = 1），按月份分组求和
        String sql = "SELECT month, " +
                "COALESCE(SUM(monthly_actual_heating), 0) as total_actual_heating " +
                "FROM qt_dp_electric_prodoper_heating " +
//                "FROM my_screen.qt_dp_electric_prodoper_heating " +
                "WHERE year = ? AND date_type = 1 " +
                "GROUP BY month " +
                "ORDER BY month";

        try {
            List<Map<String, Object>> results = jdbcTemplate.queryForList(sql, year);

            // 如果查询结果为空，所有月份默认为null（不设置值）
            if (results == null || results.isEmpty()) {
                return;
            }

            // 遍历查询结果，设置对应月份的数据
            for (Map<String, Object> row : results) {
                Integer month = (Integer) row.get("month");
                BigDecimal totalActualHeating = (BigDecimal) row.get("total_actual_heating");

                // 如果值为0，也设置（表示有数据但值为0）
                if (totalActualHeating == null) {
                    continue;
                }

                switch (month) {
                    case 1:
                        trend.setMth_1(totalActualHeating);
                        break;
                    case 2:
                        trend.setMth_2(totalActualHeating);
                        break;
                    case 3:
                        trend.setMth_3(totalActualHeating);
                        break;
                    case 4:
                        trend.setMth_4(totalActualHeating);
                        break;
                    case 5:
                        trend.setMth_5(totalActualHeating);
                        break;
                    case 6:
                        trend.setMth_6(totalActualHeating);
                        break;
                    case 7:
                        trend.setMth_7(totalActualHeating);
                        break;
                    case 8:
                        trend.setMth_8(totalActualHeating);
                        break;
                    case 9:
                        trend.setMth_9(totalActualHeating);
                        break;
                    case 10:
                        trend.setMth_10(totalActualHeating);
                        break;
                    case 11:
                        trend.setMth_11(totalActualHeating);
                        break;
                    case 12:
                        trend.setMth_12(totalActualHeating);
                        break;
                }
            }
        } catch (Exception e) {
            System.err.println("查询年份 " + year + " 的月度数据出错: " + e.getMessage());
            // 出错时不设置任何值，保持默认null
        }
    }

    /**
     * 各个电厂供热完成情况
     *
     * @param year 年份（可选，默认当前年）
     * @return 各个电厂的年度供热完成情况列表
     */
    @Override
    public List<GrPowerPlantSupplyComplateStatus> grPowerPlantSupplyComplateStatus(Integer year) {
        // 如果参数为空，使用当前年
        if (year == null) {
            year = java.time.LocalDate.now().getYear();
        }

        List<GrPowerPlantSupplyComplateStatus> result = new ArrayList<>();

        try {
            List<String> orgCodeList = Arrays.asList("10000173","10000167","10000168","10000169",
                    "10000166","10000164","10000165","10000163","10000170","10000162","10000172",
                    "10000171","10001120","10001200");
            LambdaQueryWrapper<ElectricProdoperHeating> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(ElectricProdoperHeating::getOrgCode, orgCodeList)
                    .eq(ElectricProdoperHeating::getDateType, 0)
                    .eq(ElectricProdoperHeating::getYear, year);
            List<ElectricProdoperHeating> dataList = this.list(wrapper);
            // 如果查询结果为空，返回空列表
            if (dataList == null || dataList.isEmpty()) {
                return result;
            }


            for(ElectricProdoperHeating data : dataList){
                GrPowerPlantSupplyComplateStatus vo = new GrPowerPlantSupplyComplateStatus();
                vo.setYear( year);
                vo.setPowerPlantCode(data.getOrgCode());
                vo.setPowerPlantName(data.getOrgName());
                vo.setAnnualPlanHeating(data.getAnnualPlanHeating());
                vo.setAnnualActualHeating(data.getAnnualActualHeating());
                result.add(vo);
            }

        } catch (Exception e) {
            // 如果查询出错，返回空列表，保证接口不报错
            System.err.println("查询各个电厂供热完成情况出错: " + e.getMessage());
            e.printStackTrace();
            result.clear();
        }

        return result;
    }

}
